1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.collect;
18
19 import com.google.common.annotations.GwtCompatible;
20 import com.google.common.annotations.GwtIncompatible;
21 import com.google.common.annotations.VisibleForTesting;
22 import com.google.common.base.Preconditions;
23
24 import java.io.IOException;
25 import java.io.ObjectInputStream;
26 import java.io.ObjectOutputStream;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.Map;
30 import java.util.Set;
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49 @GwtCompatible(serializable = true, emulated = true)
50 public final class HashMultimap<K, V> extends AbstractSetMultimap<K, V> {
51 private static final int DEFAULT_VALUES_PER_KEY = 2;
52
53 @VisibleForTesting
54 transient int expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
55
56
57
58
59
60 public static <K, V> HashMultimap<K, V> create() {
61 return new HashMultimap<K, V>();
62 }
63
64
65
66
67
68
69
70
71
72
73 public static <K, V> HashMultimap<K, V> create(
74 int expectedKeys, int expectedValuesPerKey) {
75 return new HashMultimap<K, V>(expectedKeys, expectedValuesPerKey);
76 }
77
78
79
80
81
82
83
84
85 public static <K, V> HashMultimap<K, V> create(
86 Multimap<? extends K, ? extends V> multimap) {
87 return new HashMultimap<K, V>(multimap);
88 }
89
90 private HashMultimap() {
91 super(new HashMap<K, Collection<V>>());
92 }
93
94 private HashMultimap(int expectedKeys, int expectedValuesPerKey) {
95 super(Maps.<K, Collection<V>>newHashMapWithExpectedSize(expectedKeys));
96 Preconditions.checkArgument(expectedValuesPerKey >= 0);
97 this.expectedValuesPerKey = expectedValuesPerKey;
98 }
99
100 private HashMultimap(Multimap<? extends K, ? extends V> multimap) {
101 super(Maps.<K, Collection<V>>newHashMapWithExpectedSize(
102 multimap.keySet().size()));
103 putAll(multimap);
104 }
105
106
107
108
109
110
111
112
113 @Override Set<V> createCollection() {
114 return Sets.<V>newHashSetWithExpectedSize(expectedValuesPerKey);
115 }
116
117
118
119
120
121
122 @GwtIncompatible("java.io.ObjectOutputStream")
123 private void writeObject(ObjectOutputStream stream) throws IOException {
124 stream.defaultWriteObject();
125 stream.writeInt(expectedValuesPerKey);
126 Serialization.writeMultimap(this, stream);
127 }
128
129 @GwtIncompatible("java.io.ObjectInputStream")
130 private void readObject(ObjectInputStream stream)
131 throws IOException, ClassNotFoundException {
132 stream.defaultReadObject();
133 expectedValuesPerKey = stream.readInt();
134 int distinctKeys = Serialization.readCount(stream);
135 Map<K, Collection<V>> map = Maps.newHashMapWithExpectedSize(distinctKeys);
136 setMap(map);
137 Serialization.populateMultimap(this, stream, distinctKeys);
138 }
139
140 @GwtIncompatible("Not needed in emulated source")
141 private static final long serialVersionUID = 0;
142 }